<template>
    <el-row>
        <el-checkbox-group v-model="checkedOptions" :min="1" :max="2">
            <el-checkbox v-for="option in dynamicOptions" :label="option.name" :key="option.id">
                <el-tag closable @close="handleClose(option)">
                    {{option.name}}
                </el-tag>
            </el-checkbox>
        </el-checkbox-group>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 选项</el-button>
    </el-row>
</template>
<script>
export default {
    data() {
        return {
            maxId: 0,
            dynamicOptions: [],
            checkedOptions: [],
            inputVisible: false,
            inputValue: ""
        };
    },
    methods: {
        handleClose(option) {
            const array = this.dynamicOptions;
            var delete_index = -1;
            for (let index = 0; index < array.length; index++) {
                const element = array[index];
                if (element.id == option.id) {
                    delete_index = index;
                    break;
                }
            }
            if (delete_index > -1) this.dynamicOptions.splice(delete_index, 1);
        },

        showInput() {
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },

        handleInputConfirm() {
            let inputValue = this.inputValue;
            if (inputValue) {
                this.maxId += 1;
                this.dynamicOptions.push({ name: inputValue, id: this.maxId });
            }
            this.inputVisible = false;
            this.inputValue = "";
            this.getValue();
        },
        getValue() {
            if (this.checkedOptions.length == 0) {
                this.$message.error("请选择一个答案");
                return;
            }
            var data = {
                content: this.dynamicOptions,
                value: this.checkedOptions
            };
            console.info(JSON.stringify(data));
        },
        parseValue(){
        }
    }
};
</script>

<style scope="this api replaced by slot-scope in 2.5.0+">
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
}
</style>


